package com.tdam2011.grupo05.control.adapters;

import com.tdam2011.grupo05.R;
import com.tdam2011.grupo05.database.manager.DataManager;
import com.tdam2011.grupo05.entities.thread.ThreadWeb;
import com.tdam2011.grupo05.entities.thread.ThreadWeb.State;

import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class ThreadCursorAdapter extends SimpleCursorAdapter {

	private static final String TAG = "ThreadCursorAdaptar";

	private final DataManager manager;
	private final LayoutInflater mInflater;

	public ThreadCursorAdapter(Context context, int layout, Cursor c,
			String[] from, int[] to, int flags) {
		super(context, layout, c, from, to, flags);
		mInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		manager = DataManager.getInstance(context);
	}

	@Override
	public View getView(int position, View contentView, ViewGroup root) {

		ThreadWeb t = manager.getThreadByCursor((Cursor) getItem(position));
		View view = null;

		if (contentView == null) {

			if (t.getState() == State.HAVE_UNREAD) {
				view = mInflater.inflate(R.layout.thread_web_item_with_message,
						root, false);

			} else {
				view = mInflater.inflate(
						R.layout.thread_web_item_without_message, root, false);
			}
			view.setTag(t);
		} else {
			view = contentView;
			if (t.getState() == State.HAVE_UNREAD
					&& ((ThreadWeb) view.getTag()).getState() == State.ALL_READED) {
				view = mInflater.inflate(R.layout.thread_web_item_with_message,
						root, false);

			}

			if (t.getState() == State.ALL_READED
					&& ((ThreadWeb) view.getTag()).getState() == State.HAVE_UNREAD) {
				view = mInflater.inflate(
						R.layout.thread_web_item_without_message, root, false);
			}
			view.setTag(t);
		}

		((TextView) view.findViewById(android.R.id.text1)).setText(t.getName());

		return view;
	}

	@Override
	public void bindView(View view, Context context, Cursor cursor) {
		Log.d(TAG, "bind view");

		super.bindView(view, context, cursor);
	}
}
